package com.objecteffects.template.web.action;

import java.io.IOException;

import com.google.inject.Inject;

import com.objecteffects.template.tumblr.TumblrResponse;
import com.objecteffects.template.tumblr.method.Avatar;
import com.objecteffects.template.util.logger.InjectLogger;
import com.objecteffects.template.web.utils.LoginRequired;
import com.objecteffects.template.web.utils.TumblrAccessToken;

import org.scribe.model.Token;

import org.slf4j.Logger;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.SimpleMessage;

/**
 * @author Rusty Wright
 */
@LoginRequired
public class AvatarActionBean extends BaseActionBean {
    @InjectLogger
    private Logger log;

    private final TumblrAccessToken tumblrAccessToken;

    @Inject
    AvatarActionBean(final TumblrAccessToken _tumblrAccessToken) {
        this.tumblrAccessToken = _tumblrAccessToken;
    }

    @DefaultHandler
    public Resolution handler() throws IOException {
        final String tumblrUrl = this.getContext().getTumblrUrl();

        if (tumblrUrl == null) {
            this.log.debug("tumblrUrl is null");

            this.getContext().getMessages()
                .add(new SimpleMessage("Tumblr url is null."));

            return new RedirectResolution(TumblrStartUrlActionBean.class);
        }

        final Token accessToken =
            this.tumblrAccessToken.fetchToken(tumblrUrl, this.getContext()
                                              .getUserId());

        final String method = "avatar/16";

        if (tumblrUrl == null || accessToken == null) {
            return new RedirectResolution(TumblrStartUrlActionBean.class);
        }

        final TumblrResponse<Avatar> built =
            new TumblrResponse.Builder<Avatar>().accessToken(accessToken)
                .blog(tumblrUrl).method(method).type(Avatar.class).build();

        final Avatar avatar = built.responseMapper();

        if (avatar == null) {
            this.getContext().getMessages()
            .add(new SimpleMessage("Permission denied."));

            return new ForwardResolution(TemplateView.ERROR);
        }

        this.getContext()
            .getMessages()
        .add(new SimpleMessage(String.format("avatar meta: %s",
                                                 avatar.getMeta())));

        this.getContext()
        .getMessages()
        .add(new SimpleMessage(String.format("avatar url: %s", avatar
                                             .getResponse().getAvatarUrl())));

        return new ForwardResolution(TemplateView.MESSAGES);
    }
}
